package com.aistar.controller;

import com.aistar.pojo.Contest;
import com.aistar.pojo.ContestMessage;
import com.aistar.pojo.Program;
import com.aistar.pojoVO.JudgeResult;
import com.aistar.pojoVO.JudgeTask;
import com.aistar.service.ContestMessageService;
import com.aistar.service.ContestService;
import com.aistar.serviceVO.ContestRankVOService;
import com.aistar.util.JudgeUtil;
import com.aistar.util.RedisMessage;
import com.aistar.util.RedisUtil;
import com.aistar.util.ServerResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Controller
@RequestMapping("/contest")

public class ContestController {
    private ContestService contestService;
    private ContestMessageService contestMessageService;
    private ContestRankVOService contestRankVOService;

    @Autowired
    public ContestController(ContestService contestService, ContestMessageService contestMessageService, ContestRankVOService contestRankVOService) {
        this.contestService = contestService;
        this.contestMessageService = contestMessageService;
        this.contestRankVOService = contestRankVOService;
    }
    //竞赛数据
    @GetMapping("/getContest")
    @ResponseBody
    public ServerResponse getContest(){
        return contestService.getRecentContest();
    }
    //排名数据
    @GetMapping("/getContestRank/{id}")
    @ResponseBody
    public ServerResponse getContestRang(@PathVariable("id")Integer contestId){
        return  contestRankVOService.getRank(contestId-1,10);
    }
    //往期竞赛回顾数据
    @GetMapping("/getPastContest/{pageNum}")
    @ResponseBody
    public ServerResponse getPastContest(@PathVariable("pageNum")Integer pageNum){
        return contestService.getPastContestByPage(pageNum);
    }

    //前往报名页面
    @RequestMapping("/goWeekContest/{id}")
    public String goWeekContest(@PathVariable("id")Integer id,HttpServletRequest request){
        request.setAttribute("contestTime",(Contest)contestService.getById(id).getData());
        request.setAttribute("id",id);
        return "contest/weekContest";
    }
    //报名页所需数据
    @RequestMapping("/getContestData/{id}")
    @ResponseBody
    public ServerResponse getContestData(@PathVariable("id")Integer id){
        Contest contest = (Contest) contestService.getById(id).getData();//获得本场比赛的信息
        List<Program> programs = new ArrayList<>();
        Program program1= (Program) contestService.getProgramById(contest.getProgramId1()).getData();
        Program program2= (Program) contestService.getProgramById(contest.getProgramId2()).getData();
        Program program3= (Program) contestService.getProgramById(contest.getProgramId3()).getData();
        programs.add(program1);
        programs.add(program2);
        programs.add(program3);
        if (programs.size()>0)
            return ServerResponse.getSuccess(programs);
        return ServerResponse.getFailed();
    }

    @RequestMapping("/getContestMessage/{contestId}/{customerId}")
    @ResponseBody
    public ServerResponse getContestMessage(@PathVariable("contestId")Integer contestId,@PathVariable("customerId")Integer customerId){
        return contestMessageService.getByContestIdAndCustomerId(contestId,customerId);
    }
    //判断是否存在该用户对应的竞赛信息表
    @RequestMapping("/getContestMessageTable/{contestId}/{customerId}")
    @ResponseBody
    public ServerResponse getContestMessageTable(@PathVariable("contestId")Integer contestId,@PathVariable("customerId")Integer customerId,HttpServletRequest request){
        ServerResponse serverResponse = contestMessageService.getByContestIdAndCustomerId(contestId,customerId);
        int status = serverResponse.getStatus();
        System.out.println("status:"+status);
        if (status == 0){
            ContestMessage contestMessage1 = new ContestMessage();
            contestMessage1.setApplyStatus(1);
            contestMessage1.setContestId(contestId);
            contestMessage1.setCustomerId(customerId);
            return contestMessageService.save(contestMessage1);
        }else if (status == 1){
            ContestMessage contestMessage2= (ContestMessage) contestMessageService.getByContestIdAndCustomerId(contestId,customerId).getData();
            if (contestMessage2.getApplyStatus() == 0){
                contestMessage2.setApplyStatus(1);
            }else {
                contestMessage2.setApplyStatus(0);
            }
            return contestMessageService.modify(contestMessage2);
        }
        return serverResponse;
    }

    //可以根据是否有开始时间时间来判断竞赛状态 和报名状态
    @RequestMapping("/determineContestStatus/{contestId}/{customerId}")
    @ResponseBody
    public ServerResponse determineContestStatus(@PathVariable("contestId")Integer contestId,@PathVariable("customerId")Integer customerId,HttpServletRequest request){
        ContestMessage contestMessage = (ContestMessage) contestMessageService.getByContestIdAndCustomerId(contestId,customerId).getData();
        if (contestMessage != null){
            request.getSession().setAttribute("contestMessageId",contestMessage.getContestMsgId());
            return ServerResponse.getSuccess(contestMessage);
        }
        return ServerResponse.getFailed();
    }
    //给竞赛信息表的开始时间赋值  即开始竞赛事件
    @RequestMapping("/sendStartTime/{contestId}/{customerId}")
    @ResponseBody
    public ServerResponse sendStartTime(@PathVariable("contestId")Integer contestId,@PathVariable("customerId")Integer customerId){
        ContestMessage contestMessage = (ContestMessage) contestMessageService.getByContestIdAndCustomerId(contestId,customerId).getData();
        contestMessage.setContestMsgStartTime(new Date());
        return contestMessageService.modify(contestMessage);
    }
    //结束竞赛的事件，给成绩赋值，并且计算花费时间
    @RequestMapping("/endContest/{contestId}/{customerId}")
    @ResponseBody
    public ServerResponse endContest(@PathVariable("contestId")Integer contestId,@PathVariable("customerId")Integer customerId){
        ContestMessage contestMessage = (ContestMessage) contestMessageService.getByContestIdAndCustomerId(contestId,customerId).getData();
        long now=new Date().getTime();
        long begin = contestMessage.getContestMsgStartTime().getTime();
        double scores = 0;
        String allResult="";
        Map<Object,Object> resultStatus = RedisUtil.hgetAll(RedisMessage.CODE_RUN_RESULT);
        for (Map.Entry<Object,Object> entry:resultStatus.entrySet()){
            Object result = entry.getValue();
            allResult += result;
            System.out.println();
            if (result == "0"){
                scores += 5;
            }
        }
        if (resultStatus.isEmpty()){//当没有做题直接提交时
            contestMessage.setOther1("444");
            contestMessage.setContestMsgMark(0.0);
        }
        contestMessage.setContestMsgThroughTime((double) (now - begin));
        contestMessage.setContestMsgMark(scores);//需要思考提交成绩的逻辑
        contestMessage.setOther1(allResult);
        RedisUtil.del(RedisMessage.CODE_RUN_RESULT);//清空redis中的数据
        return contestMessageService.modify(contestMessage);
    }

    //前往做题页面
    @RequestMapping("/goContestCompile/{id}")
    public String goContestCompile(@PathVariable("id")Integer id,HttpServletRequest request){
        Program program= (Program) contestService.getProgramById(id).getData();
        request.setAttribute("program",program);
        return "contest/contestCompile";
    }
    //向虚拟竞赛页面跳转,携带相关信息
    @RequestMapping("/goRunContest/{contestId}/{customerId}")
    public String goRunContest(@PathVariable("contestId")Integer contestId,@PathVariable("customerId")Integer customerId, HttpServletRequest request){
        ServerResponse serverResponse1 = contestRankVOService.getRank(contestId,5);//对应的比赛排名
        Contest contest = (Contest) contestService.getById(contestId).getData();//获得本场比赛的信息
        List<Program> programs = new ArrayList<>();
        Program program1= (Program) contestService.getProgramById(contest.getProgramId1()).getData();
        Program program2= (Program) contestService.getProgramById(contest.getProgramId2()).getData();
        Program program3= (Program) contestService.getProgramById(contest.getProgramId3()).getData();
        programs.add(program1);
        programs.add(program2);
        programs.add(program3);
        request.setAttribute("contestId",contestId);
        request.setAttribute("rank",serverResponse1.getData());
        request.setAttribute("programList",programs);
        return "contest/runContest";
    }
    //虚拟竞赛页点击开始虚拟竞赛按钮（不存在报名情况，点击即开始）
    @RequestMapping("/beginVirtualContest/{contestId}/{customerId}")
    @ResponseBody
    public ServerResponse beginVirtualContest(@PathVariable("contestId")Integer contestId,@PathVariable("customerId")Integer customerId){
        ContestMessage contestMessage = new ContestMessage();
        contestMessage.setContestId(contestId);
        contestMessage.setCustomerId(customerId);
        contestMessage.setStatus(2);//1表示正常的竞赛，2表示虚拟竞赛
        contestMessage.setContestMsgStartTime(new Date());
        contestMessage.setApplyStatus(1);//报名状态为1表示可以参加竞赛，考录到，一个用户可以多次参加虚拟竞赛，所以不限制虚拟竞赛在数据库中的个数
        return contestMessageService.save(contestMessage);
    }
    //判断当前虚拟竞赛是否结束
    @RequestMapping("/determineVirtualContestStatus/{contestId}/{customerId}")
    @ResponseBody
    public ServerResponse determineVirtualContestStatus(@PathVariable("contestId")Integer contestId,@PathVariable("customerId")Integer customerId,HttpServletRequest request){
//        //判断竞赛是否开始，以此来判断题目跳转的路径，当不存在时间的时候
//        ContestMessage contestMessage1 = (ContestMessage)contestMessageService.getByContestIdAndCustomerId(contestId,customerId).getData();
//        if (contestMessage1.getContestMsgMark() != null && contestMessage1.getContestMsgStartTime() != null)
//            request.setAttribute("status",0);
//        else
//            request.setAttribute("status",1);

        Object object= contestMessageService.getByContestIdAndCustomerIdAndStatus(contestId,customerId).getData();
        if (object != "查询失败"){
            ContestMessage contestMessage = (ContestMessage) object;
            request.getSession().setAttribute("contestMessageId",contestMessage.getContestMsgId());
            return ServerResponse.getSuccess(contestMessage);
        }
        return ServerResponse.getFailed();
    }
    //虚拟竞赛结束事件
    @RequestMapping("/endVirtualContest/{contestId}/{customerId}")
    @ResponseBody
    public ServerResponse endVirtualContest(@PathVariable("contestId")Integer contestId,@PathVariable("customerId")Integer customerId){
        ContestMessage contestMessage = (ContestMessage) contestMessageService.getByContestIdAndCustomerIdAndStatus(contestId,customerId).getData();
        long now=new Date().getTime();
        long begin = contestMessage.getContestMsgStartTime().getTime();
        double scores = 0;
        String allResult="";
        Map<Object,Object> resultStatus = RedisUtil.hgetAll(RedisMessage.CODE_RUN_RESULT);
        for (Map.Entry<Object,Object> entry:resultStatus.entrySet()){
            Object result = entry.getValue();
            allResult += result;
            System.out.println();
            if (result == "0"){
                scores += 5;
            }
        }
        if (resultStatus.isEmpty()){//当没有做题直接提交时
            contestMessage.setOther1("444");
            contestMessage.setContestMsgMark(0.0);
        }
        contestMessage.setContestMsgThroughTime((double) (now - begin));
        contestMessage.setContestMsgMark(scores);//需要思考提交成绩的逻辑
        contestMessage.setOther1(allResult);
        RedisUtil.del(RedisMessage.CODE_RUN_RESULT);//清空redis中的数据
        return contestMessageService.modify(contestMessage);
    }

    //执行代码
    @PostMapping("/performCode")
    @ResponseBody
    public JudgeResult performCode(@RequestBody JudgeTask judgeTask,HttpServletRequest request){
        return   JudgeUtil.doPost(judgeTask);
    }
    //提交代码
    @PostMapping("/submitCode/{contestMsgId}/{programId}")
    @ResponseBody
    public JudgeResult submitCode(@RequestBody JudgeTask judgeTask,@PathVariable("contestMsgId")Integer contestMsgId,@PathVariable("programId")Integer programId){
        JudgeResult result = JudgeUtil.doPost(judgeTask);
        Integer runStatus=result.getResult().get(0).getStatus();
        String field = contestMsgId+RedisMessage.SEPARATOR+programId;
        RedisUtil.hset(RedisMessage.CODE_RUN_RESULT,field,runStatus);//将运行结果存在redis中
        return result;
    }
}